﻿// Pulsar.cs (c) Copyright 2009, Mike Hodnick : www.hodnick.com
// This code isn't really for "musical" or "synth" purposes.  It only
// fulfills the requirements of the "pulse" feature.

using System.Collections.Generic;
using Kindohm.KSynth.Library;
using System.Windows.Threading;
using System;

namespace Kindohm.KSynth.AudioCanvas
{
    public class Pulsar
    {
        int tempo;
        int interval;
        DispatcherTimer timer;
        bool enabled;

        public Pulsar()
        {
            this.Oscillators = new List<Oscillator>();
            this.timer = new DispatcherTimer();
            this.timer.Tick += new System.EventHandler(timer_Tick);
            this.timer.Interval = TimeSpan.FromDays(1);
            this.Reset(true);
        }

        void timer_Tick(object sender, System.EventArgs e)
        {
            this.Reset();
        }

        void Reset()
        {
            for (int i = 0; i < this.Oscillators.Count; i++)
            {
                if (this.Oscillators[i].AmplitudeModulator != null)
                    this.Oscillators[i].AmplitudeModulator.Reset();
                if (this.Oscillators[i].FrequencyModulator != null)
                    this.Oscillators[i].FrequencyModulator.Reset();
                if (this.Oscillators[i].Envelope != null)
                    this.Oscillators[i].Envelope.Reset();
            }
        }

        void Reset(bool bypass)
        {
            for (int i = 0; i < this.Oscillators.Count; i++)
            {
                this.Oscillators[i].AmplitudeModulator.Reset();
                this.Oscillators[i].FrequencyModulator.Reset();
                this.Oscillators[i].AmplitudeModulator.Envelope.Active = !bypass;
                this.Oscillators[i].FrequencyModulator.Envelope.Active = !bypass;
                this.Oscillators[i].Envelope.Reset();
            }
        }

        public bool Enabled
        {
            get { return this.enabled; }
            set
            {
                this.enabled = value;
                if (this.enabled)
                {
                    this.timer.Start();
                    this.Reset(false);
                }
                else
                {
                    this.timer.Stop();
                    this.Reset(true);
                }
            }
        }

        public List<Oscillator> Oscillators
        {
            get;
            private set;
        }

        public int Tempo
        {
            set
            {
                tempo = value;
                interval = 60000 / tempo;
                this.timer.Interval = TimeSpan.FromMilliseconds(interval);
            }
            get
            {
                return tempo;
            }
        }



    }
}
